package com.ib.dataaccess;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.ib.config.ConfigurationConstants;
import com.ib.dto.TransactionAttribute;
import com.ib.enumertion.TransactionType;

/**
 * Implementation of transaction reader, when input data format is in CSV.
 */
public class CSVTransactionReader implements ITransactionReader {

	private static final Logger LOGGER = Logger.getLogger(CSVTransactionReader.class.getName());

	@Override
	public List<TransactionAttribute> readTransaction() {

		List<TransactionAttribute> transactionList = new ArrayList<TransactionAttribute>();
		try {
			InputStream fileStream = this.getClass().getResourceAsStream(ConfigurationConstants.CSV_FILE_LOCATION);
			BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream));
			String firstLine = reader.readLine();
			String eachLine = reader.readLine();
			while (eachLine != null) {
				TransactionAttribute transactionAttribute = populateTransactionAttribute(eachLine);
				transactionList.add(transactionAttribute);
				eachLine = reader.readLine();
			}
		} catch (FileNotFoundException e) {
			LOGGER.log(Level.SEVERE, "Data file was not found.");
		} catch (IOException e) {
			LOGGER.log(Level.SEVERE, "Exception raised when accessing data file.");
		}
		return transactionList;
	}

	/**
	 * This is an utility method used to parse a line and return an object of
	 * TransactionAttribute.
	 * 
	 * @param eachLine
	 * @return
	 */
	private TransactionAttribute populateTransactionAttribute(String eachLine) {

		String[] attributes = eachLine.split(",");
		TransactionAttribute attr = new TransactionAttribute();
		attr.setExternalTransactionId(attributes[0]);
		attr.setClientId(attributes[1]);
		attr.setSecurityId(attributes[2]);
		attr.setTransactionType(TransactionType.fromValue(attributes[3]));
		// Use formater to get date.
		SimpleDateFormat formater = new SimpleDateFormat(ConfigurationConstants.DATE_FORMAT);
		Date aDate = null;
		try {
			aDate = formater.parse(attributes[4]);
		} catch (ParseException e) {
			LOGGER.log(Level.SEVERE, "Could not format Date for attribute.");
		}
		attr.setDate(aDate);
		attr.setMarketValue(new BigDecimal(attributes[5]));
		if (null != attributes[6] && "Y".equals(attributes[6].trim())) {
			attr.setPriorityFlag(true);
		} else {
			attr.setPriorityFlag(false);
		}
		return attr;
	}
}